package site.anxuan.seckill.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import site.anxuan.seckill.entity.Item;
import site.anxuan.seckill.service.ItemService;
import site.anxuan.seckill.service.PromotionService;

import java.util.UUID;

@Service
@AllArgsConstructor
public class PromotionServiceImpl implements PromotionService {

    private final RedisTemplate<String, Object> redisTemplate;

    private final ItemService itemService;

    @Override
    public String generateToken(int userId, int itemId, int promotionId) {
        if (userId < 0 || itemId < 0 || promotionId < 0) {
            return null;
        }

        // 校验是否售罄
        Boolean saleOut = redisTemplate.hasKey("item:stock:out:" + itemId);
        if (saleOut != null && saleOut) {
            return null;
        }

        // 校验商品
        Item item = itemService.getByIdFromCache(itemId);
        if (item == null) item = itemService.getById(itemId);
        if (item == null) {
            return null;
        }

        // 校验活动
        if (item.getPromotion() == null
                || item.getPromotion().getId() != promotionId
                || item.getPromotion().getStatus() != 0) {
            return null;
        }

        // 获取商品令牌
        Long decrement = redisTemplate.opsForValue().decrement("item:limit:" + itemId);
        if (decrement == null || decrement < 0) {
            return null;
        }

        // 生成活动Token
        String token = UUID.randomUUID().toString();
        String key = "item:promotion:token:" + item.getId() + ":" + promotionId + ":" + userId;
        redisTemplate.opsForValue().set(key, token);
        return token;
    }
}
